<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use app\common\model\User;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use think\Db;
use think\Log;

/**
 * 充值
 *
 * @icon fa fa-circle-o
 */
class Recharge extends Backend
{

    /**
     * Recharge模型对象
     * @var \app\admin\model\Recharge
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Recharge;
        $this->view->assign("statusList", $this->model->getStatusList());
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $list = $this->model
                ->with(['Card','User','Course','Merchant'])
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);
            foreach ($list->items() as $k=>$v){
                $course_name = Db::name("course")->where(['id'=>['in',$v['course_id']]])->column("name");
                //var_dump($course_name);
                $course_name = implode(',',$course_name);
                $list->items()[$k]['course_name'] = $course_name;
            }
            $score_sum = $this->model->where($where)->with(['Card','User','Course','Merchant'])->sum("recharge.score");
            $fixed_score_sum = $this->model->where($where)->with(['Card','User','Course','Merchant'])->sum("recharge.fixed_score");

            $result = array("total" => $list->total(), "rows" => $list->items(), "extend" => ['score_sum' => $score_sum, 'fixed_score_sum' => $fixed_score_sum]);

            return json($result);
        }
        return $this->view->fetch();
    }
    public function shenhe($ids=null){
        $id = $this->request->post('id');
        $status = $this->request->post('status');
        if(!$id){
            $list = Db::name("recharge")->alias('r')
                ->field("r.*,p.name as card_name,p.name as product_name,u.nickname,m.name as merchant_name")
                ->join("card p",'r.card_id = p.id', 'LEFT')
                ->join("user u",'r.user_id = u.id', 'LEFT')
               // ->join("course c",'r.course_id = c.id', 'LEFT')
                ->join("merchant m",'r.merchant_user_id = m.id', 'LEFT')
                ->where(['r.id'=>$ids])
                ->find();
            $course_name = Db::name("course")->where(['id'=>['in',$list['course_id']]])->column("name");
            //var_dump($course_name);
            $list['course_name'] = implode(',',$course_name);
            $this->view->assign("ids", $ids);
            $this->view->assign( 'row', $list);
            return $this->view->fetch();
        }
        // exit;
        $recharge_data = Db::name("recharge")->where(['id'=>$id])->find();
        if(!$recharge_data){
            $this->error("数据有误1");
        }
        if($status == 1){
            if($recharge_data['type'] == 1){//充值积分
                $fixed_score_day = Db::name("config")->where(['name'=>'fixed_score_day'])->value('value');
                $end_time = strtotime($fixed_score_day." day");

                //$where['begintime'] = ['<',time()];
                //$where['endtime'] = ['>',time()];
                $data = Db::name("coupon")->where(['is_zs'=>1])->find();
                if(!$data){
                    $this->error("数据有误2");
                }
                if($data['received_num'] >= $data['give_num']){
                    $this->error("可领取数量不足");
                }
                $user_count = Db::name("user_coupon")->where(['user_id'=>$recharge_data['user_id'],'coupon_id'=>$data['id']])->count();
                if($user_count >= $data['allow_num']){
                    $this->error("达到每人领取数量的上限");
                }
                $in_data['coupon_id'] = $data['id'];
                $in_data['user_id'] = $recharge_data['user_id'];
                $in_data['begin_time'] = time();
                $in_data['expire_time'] = strtotime('+1 year');
                $in_data['use_begtime'] = time();
                $in_data['use_endtime'] = strtotime('+1 year');
                $in_data['money'] = $data['money'];
                $in_data['number'] = $data['number'];
                $in_data['type'] = $data['type'];
                $in_data['merchant_user_id'] = $data['merchant_user_id'];
                $in_data['createtime'] = time();
                $coupon_money = Db::name("config")->where(['name'=>'coupon_money'])->value("value");
                $floorValue = floor(($recharge_data['score']+$recharge_data['fixed_score'])/$coupon_money);
               // echo $floorValue;exit;
              if($floorValue > 0){
                  for ($i=0;$i<$floorValue;$i++){
                      Db::name("user_coupon")->insertGetId($in_data);
                  }
              }

                User::score($recharge_data['score'], $recharge_data['user_id'], '充值积分',0,$recharge_data['merchant_user_id']);
                User::score($recharge_data['fixed_score'], $recharge_data['user_id'], '充值积分',1,$recharge_data['merchant_user_id'],0,$end_time,1);
                Db::name("coupon")->where(['id'=>$data['id']])->setInc('received_num');
            }else{
                //$time = Db::name("card")->where(['id'=>$recharge_data['card_id']])->value("time");

               /* // 获取当前月份的第一天时间戳
                $firstDayOfMonth = strtotime(date('Y-m-01 00:00:00',$recharge_data['card_day']));

                // 获取当前月份的下一个月的第一天时间戳
                $end_time = strtotime(date('Y-m-01 00:00:00', strtotime('+1 month', $firstDayOfMonth)));*/
                $course_ids = explode(',',$recharge_data['course_id']);
                foreach ($course_ids as $v) {
                    $merchant_teacher_id = Db::name("course")->where(['id' => $v])->value("merchant_teacher_id");
                    $in_data['user_id'] = $recharge_data['user_id'];
                    //$in_data['card_id'] = $recharge_data['card_id'];
                    $in_data['recharge_id'] = $id;
                    // echo strtotime("+".$recharge_data['card_day']." month", time());exit;
                    if ($recharge_data['end_time']) {
                        $in_data['end_time'] = date('Y-m-d H:i:s', $recharge_data['end_time']);
                    } else {
                        $in_data['end_time'] = date('Y-m-d H:i:s', strtotime("+" . $recharge_data['card_day'] . " month", time()));
                    }

                    //$in_data['end_time'] = date('Y-m-d H:i:s',strtotime('+'.$time.' day',time()));
                    $in_data['course_id'] = $v;
                    $in_data['createtime'] = time();
                    $in_data['merchant_user_id'] = $recharge_data['merchant_user_id'];
                    $in_data['merchant_teacher_id'] = $merchant_teacher_id;
                    /* $in_data['sum'] = $sum;
                     $in_data['surplus_sum'] = $sum;*/
                    $in_data['type'] = 2;
                    Db::name("user_recharge_card")->insertGetId($in_data);

                   /* $sum = Db::name("course")->where(['id' => $recharge_data['course_id']])->value("sum");
                    $merchant_teacher_id = Db::name("course")->where(['id' => $recharge_data['course_id']])->value("merchant_teacher_id");
                    $in_data['user_id'] = $recharge_data['user_id'];
                    //$in_data['card_id'] = $recharge_data['card_id'];
                    $in_data['recharge_id'] = $id;
                    // echo strtotime("+".$recharge_data['card_day']." month", time());exit;
                    if ($recharge_data['end_time']) {
                        $in_data['end_time'] = date('Y-m-d H:i:s', $recharge_data['end_time']);
                    } else {
                        $in_data['end_time'] = date('Y-m-d H:i:s', strtotime("+" . $recharge_data['card_day'] . " month", time()));
                    }

                    //$in_data['end_time'] = date('Y-m-d H:i:s',strtotime('+'.$time.' day',time()));
                    $in_data['course_id'] = $recharge_data['course_id'];
                    $in_data['createtime'] = time();
                    $in_data['merchant_user_id'] = $recharge_data['merchant_user_id'];
                    $in_data['merchant_teacher_id'] = $merchant_teacher_id;
                    /* $in_data['sum'] = $sum;
                     $in_data['surplus_sum'] = $sum;
                    $in_data['type'] = 2;
                    Db::name("user_recharge_card")->insertGetId($in_data);*/
                }
            }
            Db::name("recharge")->where(['id'=>$id])->update(['status'=>1]);
        }else{
            Db::name("recharge")->where(['id'=>$id])->update(['status'=>2]);
        }


        $this->success("操作成功");
    }
    /**
     * 导出
     */
    public function export(){
//当前是否为关联查询
        $this->relationSearch = true;
        $filter = $this->request->param("filter");

        list($where, $sort, $order, $offset, $limit) = $this->buildparams();
        $filter = json_decode($filter,true);

        $map = [];
        if(isset($filter['information_id']))
        {
            $map['order.information_id'] = $filter['information_id'];
        }

        if(isset($filter['create_time']))
        {
            $start = substr($filter['create_time'],0,19);
            $end = substr($filter['create_time'],22);
            $map['order.create_time'] = ['between',[$start,$end]];
        }

        $map['status'] = 0;

        // 设置数据
        $lists = $this->model->alias('recharge')
            ->with(['Card','User','Course','Merchant'])
            ->field('card.name as card_name,merchant.name as merchant_name,user.mobile as user_mobile,user.nickname as user_nickname,course.name as course_name')
            ->where($where)
            ->order($sort, $order)
            ->select();

        $list = [];
        $str = ['未审核','审核通过','审核驳回'];
        $type = ['充值积分','充值卡'];
        foreach($lists as $key=>$item) {

            $list[$key]['user_mobile'] = $item['user_mobile']??'';
            $list[$key]['user_nickname'] = $item['user_nickname']??'';
            $list[$key]['merchant_name'] = $item['merchant_name']??'';
            $list[$key]['score'] = $item['score']??'';
            $list[$key]['fixed_score'] = $item['fixed_score']??'';
            $list[$key]['course_name'] = $item['course_name']??'';
            $list[$key]['card_name'] = $item['card_name']??'';
            $list[$key]['createtime'] = date('Y-m-d H:i:s',$item['createtime']);
            $list[$key]['status'] = $str[$item['status']];
            $list[$key]['type'] = $type[$item['type']-1];
        }


        $spreadsheet = new Spreadsheet();


        $sheet = $spreadsheet->getActiveSheet();
        $sheet->getStyle('A:S')->getAlignment()
            ->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER) //设置垂直居中
            ->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER) //设置水平居中
            ->setWrapText(true); //设置自动换行

        //设置表头
        $sheet->setCellValue('A1', '充值手机号');
        $sheet->setCellValue('B1', '用户昵称');
        $sheet->setCellValue('C1', '商家');
        $sheet->setCellValue('D1', '自由积分');
        $sheet->setCellValue('E1', '固定积分');
        $sheet->setCellValue('F1', '课程名称');
        $sheet->setCellValue('G1', '充值卡名称');
        $sheet->setCellValue('H1', '充值时间');
        $sheet->setCellValue('I1', '充值状态');
        $sheet->setCellValue('J1', '充值类型');



        $sheet->getColumnDimension('A')->setWidth(20);
        $sheet->getColumnDimension('B')->setWidth(20);
        $sheet->getColumnDimension('C')->setWidth(30);
        $sheet->getColumnDimension('D')->setWidth(20);
        $sheet->getColumnDimension('E')->setWidth(20);
        $sheet->getColumnDimension('F')->setWidth(30);
        $sheet->getColumnDimension('G')->setWidth(10);
        $sheet->getColumnDimension('H')->setWidth(10);
        $sheet->getColumnDimension('I')->setWidth(10);
        $sheet->getColumnDimension('J')->setWidth(10);



        $sheet->getDefaultRowDimension()->setRowHeight(30);
        $k = ['I','J','K','L','M','N','O','P','Q','R'];
        //输出表格
        foreach($list as $keys => $value) {
            $keys = $keys + 2;
            $sheet->setCellValue('A'.$keys,$value['user_mobile']??'');
            $sheet->setCellValue('B'.$keys,$value['user_nickname']??'');
            $sheet->setCellValue('C'.$keys,$value['merchant_name']??'');
            $sheet->setCellValue('D'.$keys,$value['score']??'');
            $sheet->setCellValue('E'.$keys,$value['fixed_score']??'');
            $sheet->setCellValue('F'.$keys,$value['course_name']??'');
            $sheet->setCellValue('G'.$keys,$value['card_name']??'');
            $sheet->setCellValue('H'.$keys,$value['createtime']??'');
            $sheet->setCellValue('I'.$keys,$value['status']??'');
            $sheet->setCellValue('J'.$keys,$value['type']??'');
            //var_dump($value['images']);

        }
        $filename = '导出'.date('ymdhis',time()).'.xlsx';
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Disposition: attachment;filename="'.$filename.'"');
        header('Cache-Control: max-age=0');
        $writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xlsx');
        $writer->save('php://output');

        exit;
    }
}
